/*
 * Copyright (C) 2019 ~ undefined Uniontech Software Technology Co.,Ltd.
 *
 * Author:     yanghongwei <yanghongwei@uniontech.com>
 *
 * Maintainer: yanghongwei <yanghongwei@uniontech.com>
 */

#include "../MKL25Z4.h"
#include "RGBLed.h"

RGBLed::RGBLed()
{
    init();
}
RGBLed::~RGBLed()
{
}

void RGBLed::setLedColor(int r, int g, int b)
{
    r *= 18.8;
    g *= 18.8;
    b *= 18.8;
    // TPM2 ch0->ptb18->r ch1->ptb19->g
    // TPM0 ch1->ptd1->b
    if (TPM2_MOD < r) {
        r = TPM2_MOD;
    }
    if (TPM2_MOD < g) {
        g = TPM2_MOD;
    }
    if (TPM0_MOD < b) {
        b = TPM0_MOD;
    }
    if (0 > r) {
        r = 0;
    }
    if (0 > g) {
        g = 0;
    }
    if (0 > b) {
        b = 0;
    }

    TPM2_C0V = r;
    TPM2_C1V = g;
    TPM0_C1V = b;
}

void RGBLed::init()
{
    SIM_SOPT2 |= SIM_SOPT2_TPMSRC(1);
    SIM_SOPT2 &= ~SIM_SOPT2_PLLFLLSEL_MASK;
    /* enable clocks for PORTB and PORTD */
    SIM_SCGC5 |= SIM_SCGC5_PORTB_MASK;
    SIM_SCGC5 |= SIM_SCGC5_PORTD_MASK;

    SIM_SCGC6 |= SIM_SCGC6_TPM0_MASK;
    SIM_SCGC6 |= SIM_SCGC6_TPM2_MASK;

    /* set B18, B19, D1 to GPIO */
    PORTB_PCR18 = PORT_PCR_MUX(0x3) | PORT_PCR_DSE_MASK;
    PORTB_PCR19 = PORT_PCR_MUX(0x3) | PORT_PCR_DSE_MASK;
    PORTD_PCR1 = PORT_PCR_MUX(0x4) | PORT_PCR_DSE_MASK;

    TPM0_CNT = 0;
    TPM0_MOD = 0x12c0;
    TPM0_SC = TPM_SC_CMOD(1);
    TPM0_C1SC = TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK;
    TPM0_C1V = 0;

    TPM2_CNT = 0;
    TPM2_MOD = 0x12c0;
    TPM2_SC = TPM_SC_CMOD(1);
    TPM2_C0SC = TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK;
    TPM2_C0V = 0;
    TPM2_C1SC = TPM_CnSC_MSB_MASK | TPM_CnSC_ELSA_MASK;
    TPM2_C1V = 0;
}